#!/usr/bin/perl
use strict;
use LWP::UserAgent;
use Time::Local;
use HTTP::Date;
use DBI;
use File::Compare;
use Config::IniFiles;

require "/var/myscheduler/processQC.pl";


my $cfg=Config::IniFiles->new( -file => '/var/myscheduler/dbConfig.ini');
my $db_name="rcoos";
my $db_user=$cfg->val('rcoos','username');
my $db_passwd=$cfg->val('rcoos','password');

#my $cape1="http://carocoops.org/seacoos_data/sqlite/latest.sql";
my $cape1="http://carocoops.org/obskml/feeds/latest_raw.sql";
my $cape="/home/qixiaoy/latest.sql";
my $time='100';
my $response;
my $ua=new LWP::UserAgent;

 $ua->timeout($time);
 $response=$ua->mirror($cape1,$cape);

 my(@raw_data);
 if(open(DAT, $cape)){
    @raw_data=<DAT>;
    close(DAT);
 }
 my $i=0;
 my ($sth,$sql);

 my $dbh = DBI->connect ( "dbi:Pg:dbname=$db_name", $db_user, $db_passwd);
 if ( !defined $dbh ) {
	die "Cannot connect to database!\n";
 } 

 
 my @array1;
 my $flag=0;

 foreach my $line (@raw_data){
   if(substr($line,0,1) eq " "){
      $line=substr($line,1,-1);
   }
   if((substr($line,0,6) eq "INSERT")||(substr($line,0,6) eq "UPDATE")){
      #print "***".$line;
      
       if($line=~ /INSERT into multi_obs/){
          
             $flag++;
             $line=~ s/datetime\('now'\)/current_timestamp/;
#             $line=~ s/ndbc.41110.met/cormp.ILM2.buoy/;
             @array1=split(/\,/,$line);
             my $count=@array1;
             my $platform_handle=$array1[($count/2)+1];

             #$platform_handle."\n";
             $sql="select row_id from platform where platform_handle=$platform_handle";
             $sth = $dbh->prepare( $sql );
	     $sth->execute();
             my $rows_returned = $sth->rows;		
	     $sth->finish;
             
             if($rows_returned){   
                  $sth = $dbh->prepare( $line );
               #   print $line;

                  $sth->execute();
                  $sth->finish();
             }
        }
        else {
                  $sth = $dbh->prepare( $line );
                  $sth->execute();
                  $sth->finish();
        }
    }     
 }

 $dbh->disconnect();

 if($flag>0){
    system("perl /var/www/cgi-bin/gnugraph/rcoos/generateStationHTML1.pl");
 } 
 system("rm $cape");
 exit 0;
